import { Router } from 'express'

const router = Router()

function generateQuestions(subject, difficulty, count) {
  const questions = []
  for (let i = 0; i < count; i++) {
    let question
    switch (subject) {
      case 'number-line':
        question = generateNumberLineQuestion(difficulty)
        break
      case 'fraction':
        question = generateFractionQuestion(difficulty)
        break
      case 'geometry':
        question = generateGeometryQuestion(difficulty)
        break
      case 'function':
        question = generateFunctionQuestion(difficulty)
        break
      default:
        question = generateNumberLineQuestion(difficulty)
    }
    questions.push({ id: Date.now() + i, ...question })
  }
  return questions
}

function generateNumberLineQuestion(difficulty) {
  const min = difficulty === 'easy' ? -10 : difficulty === 'medium' ? -50 : -100
  const max = difficulty === 'easy' ? 10 : difficulty === 'medium' ? 50 : 100
  const num1 = Math.floor(Math.random() * (max - min + 1)) + min
  const num2 = Math.floor(Math.random() * (max - min + 1)) + min
  return {
    type: 'number-line',
    question: `在数轴上，${num1} 和 ${num2} 哪个更大？`,
    options: [
      { value: num1, label: `${num1}` },
      { value: num2, label: `${num2}` },
    ],
    correctAnswer: Math.max(num1, num2),
    explanation: `在数轴上，右边的数比左边的数大。${Math.max(num1, num2)} 比 ${Math.min(num1, num2)} 大。`,
  }
}

function generateFractionQuestion(difficulty) {
  const denominators =
    difficulty === 'easy'
      ? [2, 3, 4]
      : difficulty === 'medium'
        ? [2, 3, 4, 5, 6]
        : [2, 3, 4, 5, 6, 7, 8, 9]
  const den1 = denominators[Math.floor(Math.random() * denominators.length)]
  const den2 = denominators[Math.floor(Math.random() * denominators.length)]
  const num1 = Math.floor(Math.random() * den1) + 1
  const num2 = Math.floor(Math.random() * den2) + 1
  return {
    type: 'fraction',
    question: `比较分数 ${num1}/${den1} 和 ${num2}/${den2} 的大小`,
    options: [
      { value: 'first', label: `${num1}/${den1} 更大` },
      { value: 'second', label: `${num2}/${den2} 更大` },
      { value: 'equal', label: '相等' },
    ],
    correctAnswer: compareFractions(num1, den1, num2, den2),
    explanation: `通分后比较：${num1}/${den1} = ${num1 * den2}/${den1 * den2}, ${num2}/${den2} = ${num2 * den1}/${den1 * den2}`,
  }
}

function compareFractions(num1, den1, num2, den2) {
  const cross1 = num1 * den2
  const cross2 = num2 * den1
  if (cross1 > cross2) return 'first'
  if (cross1 < cross2) return 'second'
  return 'equal'
}

function generateGeometryQuestion(difficulty) {
  const shapes = ['rectangle', 'circle', 'triangle']
  const shape = shapes[Math.floor(Math.random() * shapes.length)]
  let question, correctAnswer, explanation
  switch (shape) {
    case 'rectangle': {
      const width = Math.floor(Math.random() * 10) + 1
      const height = Math.floor(Math.random() * 10) + 1
      question = `计算长为 ${width}，宽为 ${height} 的矩形面积`
      correctAnswer = width * height
      explanation = `矩形面积 = 长 × 宽 = ${width} × ${height} = ${correctAnswer}`
      break
    }
    case 'circle': {
      const radius = Math.floor(Math.random() * 10) + 1
      question = `计算半径为 ${radius} 的圆的面积`
      correctAnswer = Math.PI * radius * radius
      explanation = `圆的面积 = π × r² = π × ${radius}² = ${correctAnswer.toFixed(2)}`
      break
    }
    case 'triangle': {
      const base = Math.floor(Math.random() * 10) + 1
      const height = Math.floor(Math.random() * 10) + 1
      question = `计算底为 ${base}，高为 ${height} 的三角形面积`
      correctAnswer = (base * height) / 2
      explanation = `三角形面积 = (底 × 高) ÷ 2 = (${base} × ${height}) ÷ 2 = ${correctAnswer}`
      break
    }
  }
  return {
    type: 'geometry',
    question,
    correctAnswer: Math.round(correctAnswer * 100) / 100,
    explanation,
  }
}

function generateFunctionQuestion(difficulty) {
  const coefficients =
    difficulty === 'easy' ? [1, 2] : difficulty === 'medium' ? [1, 2, 3] : [1, 2, 3, 4, 5]
  const a = coefficients[Math.floor(Math.random() * coefficients.length)]
  const b = Math.floor(Math.random() * 10) - 5
  const x = Math.floor(Math.random() * 10) - 5
  const y = a * x + b
  return {
    type: 'function',
    question: `函数 y = ${a}x + ${b}，当 x = ${x} 时，y = ?`,
    correctAnswer: y,
    explanation: `将 x = ${x} 代入函数：y = ${a} × ${x} + ${b} = ${y}`,
  }
}

router.post('/generate', (req, res) => {
  const { subject, difficulty, count = 5 } = req.body
  try {
    const questions = generateQuestions(subject, difficulty, count)
    res.json({ code: 200, data: questions, msg: '生成题目成功' })
  } catch (e) {
    res.status(400).json({ code: 400, data: null, msg: '生成题目失败: ' + e.message })
  }
})

router.get('/types', (_req, res) => {
  const questionTypes = [
    {
      type: 'number-line',
      name: '数轴题目',
      description: '学习数轴上的数字比较和位置关系',
      difficulties: ['easy', 'medium', 'hard'],
    },
    {
      type: 'fraction',
      name: '分数题目',
      description: '学习分数的比较和计算',
      difficulties: ['easy', 'medium', 'hard'],
    },
    {
      type: 'geometry',
      name: '几何题目',
      description: '学习基本几何图形的面积计算',
      difficulties: ['easy', 'medium', 'hard'],
    },
    {
      type: 'function',
      name: '函数题目',
      description: '学习线性函数的计算和应用',
      difficulties: ['easy', 'medium', 'hard'],
    },
  ]
  res.json({ code: 200, data: questionTypes, msg: '获取题目类型成功' })
})

export default router
